﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TZ.PlugIn.FileSrv
{
    [Description("采购订单列表撤回或作废合同文件")]
    public class PurListRecallFile : AbstractListPlugIn
    {
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);
            //列表撤回合同
            if (e.BarItemKey.EqualsIgnoreCase("tbListRecallFile"))
            {
                var seList = this.ListView.SelectedRowsInfo;
                foreach (var row in seList)
                {
                    var BillNo = row.BillNo;
                    var InterId = row.PrimaryKeyValue;
                    string sqlStr = string.Format("SELECT FCONTRACTID,FisRecallBill,FisCancelBill FROM T_PUR_POORDER WHERE FBILLNO='{0}'", BillNo);
                    var FContractId = "";
                    var ContractIds = DBUtils.ExecuteDynamicObject(this.Context, sqlStr);
                    if (ContractIds.Count > 0)
                    {
                        FContractId = ContractIds[0][0].ToString();
                    }
                    if (FContractId == "")
                    {
                        this.View.ShowMessage("没有创建电子签约单！");
                        //break;
                    }
                    var top1Row = ContractIds[0];
                    //var abc = top1Row["FisRecallBill"];
                    //var FisRecallBill = Convert.ToBoolean(Convert.ToInt32(top1Row["FisRecallBill"]));
                    //if (FisRecallBill)
                    //{
                    //    this.View.ShowMessage("没有创建电子签约单！");
                    //}
                    var ErrMsg = "";
                    var isPost = true;
                    Common.GetParams(this.Context);
                    var result = Common.PostRecall(Common.RecallBillUrl, Common.AppToken, Common.AppSecret, FContractId, "金蝶撤回", ref isPost);
                    if (!isPost)
                    {
                        ErrMsg = result.ToString().Trim();
                        this.View.ShowErrMessage(ErrMsg);
                    }
                    else
                    {
                        var JsonResult = result as JObject;
                        if (JsonResult["code"].ToString() != "0")
                        {
                            ErrMsg = "code【" + JsonResult["code"].ToString().Trim() + "】,message【" + JsonResult["message"].ToString().Trim() + "】";
                            var sql = string.Format("update T_PUR_POORDER set FRECMESSAGE = '{1}' where FBILLNO = '{0}'", BillNo, ErrMsg);
                            DBUtils.Execute(this.Context, sql);
                            this.View.ShowErrMessage(ErrMsg);
                        }
                        else
                        {
                            var sql = string.Format("update T_PUR_POORDER set FISRECALLBILL = 1,FRECMESSAGE = '撤回成功' where FBILLNO = '{0}'", BillNo);
                            DBUtils.Execute(this.Context, sql);
                            this.View.ShowMessage("撤回成功！");

                            //撤回时删除已经上传的附件
                            //var InterId = this.View.Model.DataObject["Id"].ToString();
                            var FileName = BillNo + ".PDF";//定义文件名：单据编号为文件名
                            sql = string.Format("SELECT  FID FROM T_BAS_ATTACHMENT WHERE FBILLTYPE = '{0}' AND FINTERID = '{1}' and FATTACHMENTNAME = '{2}'", "PUR_PurchaseOrder", InterId, FileName);
                            var dyExists = DBUtils.ExecuteDynamicObject(this.Context, sql);
                            var delAttchmentIds = new List<string>();
                            if (dyExists.Count > 0)
                            {
                                foreach (var dye in dyExists)
                                {
                                    delAttchmentIds.Add(dye["FID"].ToString());//构建需要删除的FID集合 
                                }
                            }

                            if (delAttchmentIds.Count > 0)
                            {
                                FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, "BOS_Attachment");

                                DynamicObjectType wlType = meta.BusinessInfo.GetDynamicObjectType();

                                BusinessDataServiceHelper.Delete(this.Context, delAttchmentIds.ToArray(), meta.BusinessInfo.GetDynamicObjectType());
                            }
                        }
                    }

                    //this.ListView.ShowMessage("确实要撤回吗？", MessageBoxOptions.YesNo,
                    //new Action<MessageBoxResult>((MsgResult) =>
                    //{
                    //    if (MsgResult == MessageBoxResult.Yes)
                    //    {

                    //    }
                    //    else
                    //        return;
                    //}));
                }
                //var rowDatas = this.ListModel.GetData(seList);
            }
            //
            if (e.BarItemKey.EqualsIgnoreCase("tbListCancelFile"))
            {
                var seList = this.ListView.SelectedRowsInfo;
                foreach (var row in seList)
                {
                    var BillNo = row.BillNo;
                    var InterId = row.PrimaryKeyValue;
                    string sqlStr = string.Format("SELECT FCONTRACTID,FisRecallBill,FisCancelBill FROM T_PUR_POORDER WHERE FBILLNO='{0}'", BillNo);
                    var FContractId = "";
                    var ContractIds = DBUtils.ExecuteDynamicObject(this.Context, sqlStr);
                    if (ContractIds.Count > 0)
                    {
                        FContractId = ContractIds[0][0].ToString();
                    }
                    if (FContractId == "")
                    {
                        this.View.ShowMessage("没有创建电子签约单！");
                        //break;
                    }
                    var top1Row = ContractIds[0];
                    var FisCancelBill = Convert.ToBoolean(Convert.ToInt32(top1Row["FisCancelBill"]));

                    //var BillNo = this.View.Model.GetValue("FBillNo").ToString();
                    var PKID = InterId;
                    Common.GetParams(this.Context);
                    var sql = string.Format("exec SP_QYS_GetJsonPurOrderCancelBill {0},{1},'{2}'", PKID, FContractId, this.Context.UserName);
                    var dycollJson = DBUtils.ExecuteDynamicObject(this.Context, sql);
                    if (dycollJson.Count < 1)
                    {
                        this.View.ShowMessage("获取发起作废报文异常");
                        return;
                    }
                    var JsonData = JObject.Parse(dycollJson[0][0].ToString());
                    var ErrMsg = "";
                    var isPost = true;
                    var result = Common.PostBill(Common.CancelBillUrl, Common.AppToken, Common.AppSecret, JsonData, ref isPost);
                    if (!isPost)
                    {
                        ErrMsg = result.ToString().Trim();
                        string sqlerr = string.Format("update T_PUR_POORDER set FCCLMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                        DBUtils.Execute(this.Context, sqlerr);
                        this.View.ShowErrMessage("发起作废失败：" + ErrMsg);
                        return;
                    }
                    else
                    {
                        var JsonResult = result as JObject;
                        if (JsonResult["code"].ToString() != "0")
                        {
                            ErrMsg = "code【" + JsonResult["code"].ToString().Trim() + "】,message【" + JsonResult["message"].ToString().Trim() + "】";
                            string sqlerr = string.Format("update T_PUR_POORDER set FCCLMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                            DBUtils.Execute(this.Context, sqlerr);
                            this.View.ShowErrMessage("发起作废失败：" + ErrMsg);
                            return;
                        }
                        else
                        {
                            sql = string.Format("update T_PUR_POORDER set FISCANCELBILL = 1,FCCLMESSAGE = '作废成功' where FID = {0}", PKID);
                            DBUtils.Execute(this.Context, sql);
                            this.View.ShowMessage("作废成功！");

                            //撤回时删除已经上传的附件
                            //var InterId = this.View.Model.DataObject["Id"].ToString();
                            var FileName = BillNo + ".PDF";//定义文件名：单据编号为文件名
                            sql = string.Format("SELECT  FID FROM T_BAS_ATTACHMENT WHERE FBILLTYPE = '{0}' AND FINTERID = '{1}' and FATTACHMENTNAME = '{2}'", "PUR_PurchaseOrder", InterId, FileName);
                            var dyExists = DBUtils.ExecuteDynamicObject(this.Context, sql);
                            var delAttchmentIds = new List<string>();
                            if (dyExists.Count > 0)
                            {
                                foreach (var dye in dyExists)
                                {
                                    delAttchmentIds.Add(dye["FID"].ToString());//构建需要删除的FID集合 
                                }
                            }

                            if (delAttchmentIds.Count > 0)
                            {
                                FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, "BOS_Attachment");

                                DynamicObjectType wlType = meta.BusinessInfo.GetDynamicObjectType();

                                BusinessDataServiceHelper.Delete(this.Context, delAttchmentIds.ToArray(), meta.BusinessInfo.GetDynamicObjectType());
                            }

                        }
                    }

                    //this.ListView.ShowMessage("确实要发起作废吗？", MessageBoxOptions.YesNo,
                    //new Action<MessageBoxResult>((MsgResult) =>
                    //{
                    //    if (MsgResult == MessageBoxResult.Yes)
                    //    {

                    //    }
                    //    else
                    //        return;
                    //}));
                }
            }
        }
    }
}
